<template>
  <el-tree-select
    v-bind="$attrs"
    v-model="value"
    :data="_data"
    style="width: 100%"
    filterable
    clearable
    :collapse-tags="props.collapseTags"
    :max-collapse-tags="props.maxCollapseTags"
    :multiple="props.multiple"
    :filter-node-method="filterNodeMethod"
  />
</template>

<script setup lang="ts">
import { computed, watch, ref } from 'vue'

import treeProps, { emit, buildTreeKeys } from './props.ts'
import { cloneDeep } from 'lodash-es'

const props = defineProps(treeProps)
const emits = defineEmits(emit)

const _data = ref<any>([])

const value = computed({
  get: () => {
    return props.modelValue
  },
  set: (value: any) => {
    emits('update:modelValue', value)
  }
})

watch(
  () => props.data,
  (newValue) => {
    // cloneDeep 防止递归修改源数据导致递归溢出
    _data.value = buildTreeKeys(props.fields, cloneDeep(newValue))
  },
  {
    deep: true
  }
)

const filterNodeMethod = (value: any, data: Record<string, any>) =>
  data.label.includes(value)

defineOptions({
  name: 'CETreeSelect',
  inheritAttrs: false
})
</script>

<style lang="scss">
.tree_title {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
